#include "mem.h"

#include "assert.h"

#include <stdlib.h>

const Except_T ex_mem_alloc_failed = {"memory alloc failed"};

void* Mem_alloc(long nbytes, const char *file, int line) {
	assert(nbytes > 0);
	void *ptr = malloc(nbytes);
	if (ptr == NULL) {
		if (file)
			except_raise(&ex_mem_alloc_failed, file, line);
		else
			RAISE(ex_mem_alloc_failed);
	}
	return ptr;
}

void* Mem_calloc(long count, long nbytes, const char *file, int line) {
	assert(count > 0);
	assert(nbytes > 0);
	void *ptr = calloc(count, nbytes);
	if (ptr == NULL) {
		if (file)
			except_raise(&ex_mem_alloc_failed, file, line);
		else
			RAISE(ex_mem_alloc_failed);
	}
	return ptr;
}

void* Mem_resize(void *ptr, long nbytes, const char *file, int line) {
	assert(ptr);
	assert(nbytes > 0);
	void *ret = realloc(ptr, nbytes);
	if (ret == NULL) {
		if (file)
			except_raise(&ex_mem_alloc_failed, file, line);
		else
			RAISE(ex_mem_alloc_failed);
	}
	return ret;
}

void Mem_free(void *ptr, const char *file, int line) {
    (void)file;
    (void)line;
	if (ptr)
		free(ptr);
}
